package com.easylinkin.linkappapi.machinery.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easylinkin.linkappapi.common.exceptions.BusinessException;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.lobar.dto.UserCertificateDTO;
import com.easylinkin.linkappapi.lobar.entity.UserCertificate;
import com.easylinkin.linkappapi.lobar.service.UserCertificateService;
import com.easylinkin.linkappapi.machinery.dto.MachineryUserLinkDTO;
import com.easylinkin.linkappapi.machinery.entity.MachineryUserLink;
import com.easylinkin.linkappapi.machinery.mapper.MachineryUserLinkMapper;
import com.easylinkin.linkappapi.machinery.service.MachineryUserLinkService;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * <p>
 * 闸机表 服务实现类
 * </p>
 *
 * @author TongJie
 * @since 2022-04-13
 */
@Service
public class MachineryUserLinkServiceImpl extends ServiceImpl<MachineryUserLinkMapper, MachineryUserLink> implements
    MachineryUserLinkService {

  @Resource
  private LinkappUserContextProducer linkappUserContextProducer;

  @Autowired
  private UserCertificateService userCertificateService;

  /**
   * 增加
   * @param machineryUserLinkDTO
   */
  @Override
  public void insert(MachineryUserLinkDTO machineryUserLinkDTO) {
    MachineryUserLink machineryUserLink = BeanUtil
        .toBean(machineryUserLinkDTO, MachineryUserLink.class);
    /**
     * 验证重复
     */
    this.checkExist(machineryUserLink);
    //设置基本属性
    this.setBase(machineryUserLink);
    //设置证书
    if (null != machineryUserLinkDTO.getCertificateIds() && machineryUserLinkDTO.getCertificateIds().size() > 0){
      machineryUserLink.setCertificateId(StringUtils.join(machineryUserLinkDTO.getCertificateIds(),","));
    }
    this.save(machineryUserLink);
  }

  /**
   * 根据id编辑
   * @param machineryUserLinkDTO
   */
  @Override
  public void updateOne(MachineryUserLinkDTO machineryUserLinkDTO) {
    MachineryUserLink machineryUserLink = BeanUtil
        .toBean(machineryUserLinkDTO, MachineryUserLink.class);
    /**
     * 验证重复
     */
    this.checkExist(machineryUserLink);
    //设置基本属性
    this.setBase(machineryUserLink);
    //设置证书
    if (null != machineryUserLinkDTO.getCertificateIds() && machineryUserLinkDTO.getCertificateIds().size() > 0){
      machineryUserLink.setCertificateId(StringUtils.join(machineryUserLinkDTO.getCertificateIds(),","));
    }else {
      machineryUserLink.setCertificateId(null);
    }
    this.updateById(machineryUserLink);
  }

  @Override
  public IPage<MachineryUserLinkDTO> queryListByPage(RequestModel<MachineryUserLinkDTO> requestModel) {
    //查询所有证书
    List<UserCertificateDTO> certificateDTOS = userCertificateService
        .queryList(new UserCertificate());
    Page page = requestModel.getPage();
    MachineryUserLink machineryUserLink = requestModel.getCustomQueryParams();
    Assert.notNull(machineryUserLink.getTypeId(), "类别id不能为空");
    IPage<MachineryUserLinkDTO> machineryUserLinkIPage = baseMapper.queryListByPage(page, machineryUserLink);
    machineryUserLinkIPage.getRecords().forEach(m ->{
      //设置一个证书默认状态
      List<String> status = new ArrayList<>();
      status.add("证书缺失");
      m.setAge(DateUtil.age(m.getBirthday(),new Date()));
      //设置证书状态
      String certificateId = m.getCertificateId();
      if (StringUtils.isNotBlank(certificateId)){
        String[] strings = certificateId.split(",");
        List<String> certificates = new ArrayList<>(Arrays.asList(strings));
        if (null != certificateDTOS && certificateDTOS.size() > 0){
          List<UserCertificateDTO> dtos = certificateDTOS.stream()
              .filter(c -> certificates.contains(c.getId()))
              .collect(Collectors.toList());
          if (null != dtos && dtos.size() > 0){
            status.clear();
            //查找正常的
            List<UserCertificateDTO> dtoList = dtos.stream()
                .filter(d -> !Integer.valueOf(1).equals(d.getStatus()))
                .collect(Collectors.toList());
            if (dtoList.size() > 0){
              dtos.forEach(d ->{
                if (Integer.valueOf(1).equals(d.getStatus())){
                  status.add(d.getName() + "正常");
                }else {
                  status.add(d.getName() + (Integer.valueOf(2).equals(d.getStatus())?"即将过期":"已过期"));
                }
              });
            }else {
              status.add("正常");
            }
          }
        }
      }
      m.setCertificateStatus(status);
    });
    return machineryUserLinkIPage;
  }

  /**
   * 验证重复
   */
  private void checkExist(MachineryUserLink machineryUserLink) {
    QueryWrapper<MachineryUserLink> queryWrapper = new QueryWrapper<>();
    //设置判断重复条件
    queryWrapper.eq("user_id_",machineryUserLink.getUserId())
        .eq("type_id_",machineryUserLink.getTypeId());
    //编辑的时候存在id
    Optional.ofNullable(machineryUserLink.getId()).ifPresent(id -> queryWrapper.ne("id",machineryUserLink.getId()));
    Integer integer = baseMapper.selectCount(queryWrapper);
    if (integer>0){
      throw new BusinessException("该人员已存在");
    }
  }

  /**
   * 设置基本属性
   * @param machineryUserLink
   */
  private void setBase(MachineryUserLink machineryUserLink) {
    machineryUserLink.setModifyTime(new Date());
    machineryUserLink.setModifyId(linkappUserContextProducer.getCurrent().getId());
    //没有id就是新增,有就是编辑
    if (null == machineryUserLink.getId()){
      machineryUserLink.setCreatorId(linkappUserContextProducer.getCurrent().getId());
      machineryUserLink.setCreateTime(new Date());
      machineryUserLink.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
    }
  }
}
